package org.wzl.todolisthelper.utils;

import com.fasterxml.jackson.core.type.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.Map;

@Slf4j
public class RestTemplateUtil {

    public static String post(String url, Map<String, Object> parameter) {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(parameter, requestHeaders);
        return restTemplate.postForObject(url, requestEntity, String.class);
    }

    public static String get(String url, Map<String, Object> parameter) {
        if (!parameter.isEmpty()) {
            StringBuilder urlBuilder = new StringBuilder(url + "?");
            for (String key : parameter.keySet()) {
                urlBuilder.append(key).append("=").append(parameter.get(key)).append("&");
            }
            url = urlBuilder.toString();
            url = url.substring(0, url.length() - 1);
        }
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        return restTemplate.getForEntity(url, String.class, parameter).getBody();
    }

    public static <T> T get(String url, Map<String, Object> parameter, Class<T> clazz) {
        return JsonWrapperUtil.parseJson(get(url, parameter), clazz);
    }

    public static <T> T get(String url, Map<String, Object> parameter, TypeReference<T> type) {
        return JsonWrapperUtil.parseJson(get(url, parameter), type);
    }

    public static <T> T post(String url, Map<String, Object> parameter, Class<T> clazz) {
        return JsonWrapperUtil.parseJson(post(url, parameter), clazz);
    }

    public static <T> T post(String url, Map<String, Object> parameter, TypeReference<T> type) {
        return JsonWrapperUtil.parseJson(post(url, parameter), type);
    }
}